# 操作验收台数据
from fastapi import APIRouter, Header
from sqlalchemy import create_engine
from sqlalchemy.exc import OperationalError
from sqlalchemy.orm import sessionmaker

from config import MYSQL_CONFIG
from model.db import engine
from model.db.connect import create_tenant_engine, create_tables, create_project_tables
from model.db.mapper.project_mapper import add_project, get_project, get_share_project, delete_project, \
    get_project_by_id, update_project
from model.db.mapper.well_mapper import init_core_param
from model.params.project_params import deleteParam, updateParam

from model.params.users_params import ProjectParam, UserID, ProjID
from util import success_res, obj_to_dict, SuccessCode, error_res, ErrorCode, objs_to_dict
from util.access_token import parse_token

project_router = APIRouter(prefix="/project", tags=['项目管理'])


@project_router.post("/add", name="添加项目")
async def add_pro(param: ProjectParam, token=Header('token')):
    pro = add_project(param)
    try:
        # 创建数据库
        conn = engine.connect()
        conn.execute("commit")
        conn.execute("create database project" + str(pro.project_id))
        conn.close()

        # 初始化数据库
        new_engine = create_tenant_engine("project" + str(pro.project_id))
        create_project_tables(new_engine)
        # 创建数据库会话
        newSession = sessionmaker(autocommit=False, autoflush=False, bind=new_engine)
        # 创建公共session对象:
        project_sensitivity = newSession()
        init_core_param(project_sensitivity)
    except Exception as e:
        print(e)
        raise e

    return success_res(obj_to_dict(pro), SuccessCode.POST)


@project_router.post("/get", name="获取项目")
async def get_pro(param: UserID, token=Header('token')):
    # payload = parse_token(token)
    # if payload.get('user_id') != param.user_id:
    #     return error_res(ErrorCode.USER_NO_PERMISSION)
    projs = get_project(param.user_id)

    return success_res(objs_to_dict(projs), SuccessCode.POST)


@project_router.post("/getShare", name="获取共享项目")
async def get(token=Header('token')):
    projs = get_share_project()
    return success_res(objs_to_dict(projs), SuccessCode.GET)


@project_router.post("/getProj", name="通过id获取项目")
async def get(param: ProjID,token=Header('token')):
    proj = get_project_by_id(param.proj_id)
    return success_res(obj_to_dict(proj), SuccessCode.GET)


@project_router.post("/delete", name="删除项目信息")
async def get(delete:deleteParam,token=Header('token')):
    # payload = parse_token(token)
    # project = get_project_by_id(delete.project_id)
    # if payload.get('user_id') != project.create_user:
    #     return error_res(ErrorCode.USER_NO_PERMISSION)
    # 删除数据库
    conn = engine.connect()
    conn.execute("commit")
    conn.execute("drop database project" + str(delete.project_id))
    conn.close()

    delete_project(delete.project_id)
    return success_res("", SuccessCode.DELETE)


@project_router.post("/update", name="更新项目信息")
async def get(param:updateParam,token=Header('token')):
    # payload = parse_token(token)
    # project = get_project_by_id(updateParam.project_id)
    # if payload.get('user_id') != project.create_user:
    #     return error_res(ErrorCode.USER_NO_PERMISSION)
    project = update_project(param.project_id,param.project_name,param.is_share,param.remark)
    return success_res('success', SuccessCode.POST)
